package com.sphd.restaurantsystem.activitys;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.gprinter.aidl.GpService;
import com.gprinter.command.EscCommand;
import com.gprinter.command.GpCom;
import com.gprinter.io.GpDevice;
import com.gprinter.io.PortParameters;
import com.gprinter.save.PortParamDataBase;
import com.gprinter.service.GpPrintService;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.adapters.BluetoothPtrinterAdapter;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.info.BlueToothPrinterInfo;

import org.apache.commons.lang.ArrayUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/*
* 添加打印机
* */
public class AddPrinterActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.printer_info_text)
    TextView printerInfoText;
    @BindView(R.id.test_printer)
    Button testPrinter;
    @BindView(R.id.printer_list_num)
    RecyclerView printerListNum;
    private Intent intent;
    private BluetoothAdapter mBluetoothAdapter;
    private GpService mGpService;
    private PrinterServiceConnection conn = null;
    private PortParameters mPortParam = new PortParameters();
    private List<BlueToothPrinterInfo> bluetoothPrinterList;
    private BluetoothPtrinterAdapter bluetoothPtrinterAdapter;
    public static final String ACTION_CONNECT_STATUS = "action.connect.status";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_printer);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v ->finish() );
    }

    private void initView() {
        intent = new Intent();
        setTitleBar(toolbar,"添加打印机");
        setRecy(printerListNum);
        startService();
        connection();
        initPortParam();
        registerBroadcast();
        bluetoothPrinterList = new ArrayList<BlueToothPrinterInfo>();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                BlueToothPrinterInfo blueToothPrinterInfo = new BlueToothPrinterInfo();
                blueToothPrinterInfo.setName(device.getName());
                blueToothPrinterInfo.setMacadd(device.getAddress());
                bluetoothPrinterList.add(blueToothPrinterInfo);
            }
            mPortParam.setPortType(PortParameters.BLUETOOTH);
        } else {
            String noDevices = getResources().getText(R.string.none_paired)
                    .toString();

        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mFindBlueToothReceiver, filter);
        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mFindBlueToothReceiver, filter);
        // Get the local Bluetooth adapter

        bluetoothPtrinterAdapter = new BluetoothPtrinterAdapter(bluetoothPrinterList);
        printerListNum.setAdapter(bluetoothPtrinterAdapter);

    }

    @OnClick(R.id.test_printer)
    public void onClick() {
        if ("已连接".equals(printerInfoText.getText().toString())) {
            sendReceipt();
        }
    }

    private void sendReceipt() {
        EscCommand esc = new EscCommand();
        esc.addPrintAndFeedLines((byte) 3);
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印居中
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);//设置为倍高倍宽
        esc.addText("Sample\n");   //  打印文字
        esc.addPrintAndLineFeed();

		/*打印文字*/
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);//取消倍高倍宽
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);//设置打印左对齐
        esc.addText("Print text\n");   //  打印文字

        esc.addText("小帅哥常来玩啊\n");   //  打印文字
        esc.addText("Welcome 张坤!\n");   //  打印文字



		/*打印文字*/
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印左对齐
        esc.addText("Completed!\r\n");   //  打印结束
        esc.addPrintAndFeedLines((byte) 8);

        Vector<Byte> datas = esc.getCommand(); //发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = ArrayUtils.toPrimitive(Bytes);
        String str = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rel;
        try {
            rel = mGpService.sendEscCommand(0, str);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
            if (r != GpCom.ERROR_CODE.SUCCESS) {
                Toast.makeText(getApplicationContext(), GpCom.getErrorText(r),
                        Toast.LENGTH_SHORT).show();
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private final BroadcastReceiver mFindBlueToothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed
                // already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {


                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_bluetooth_device);


            }
        }
    };
    private void initPortParam() {

//        boolean[] state = getConnectState();
        PortParamDataBase database = new PortParamDataBase(this);
        mPortParam = new PortParameters();
        mPortParam = database.queryPortParamDataBase("" + 0);
        mPortParam.setPortOpenState(false);
//		}
    }
    //启动打印服务
    private void startService() {
        intent.setClass(context, GpPrintService.class);
        startService(intent);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //绑定服务
    private void connection() {
        conn = new PrinterServiceConnection();
        Intent intent = new Intent();
        intent.setAction("com.gprinter.aidl.GpPrintService");
        intent.setPackage(getPackageName());
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
    }

    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {

            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
        }
    }

    private void registerBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_CONNECT_STATUS);
        this.registerReceiver(PrinterStatusBroadcastReceiver, filter);
    }
    private BroadcastReceiver PrinterStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_CONNECT_STATUS.equals(intent.getAction())) {
                int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);
                int id = intent.getIntExtra(GpPrintService.PRINTER_ID, 0);
                if (type == GpDevice.STATE_CONNECTING) {
                    setProgressBarIndeterminateVisibility(true);
//					SetLinkButtonEnable(ListViewAdapter.DISABLE);
                    printerInfoText.setText("未连接");
                    mPortParam.setPortOpenState(false);

                } else if (type == GpDevice.STATE_NONE) {
                    setProgressBarIndeterminateVisibility(false);
//					SetLinkButtonEnable(ListViewAdapter.ENABLE);
                    printerInfoText.setText("已连接");
                    mPortParam.setPortOpenState(false);
                } else if (type == GpDevice.STATE_VALID_PRINTER) {
                    setProgressBarIndeterminateVisibility(false);
//					SetLinkButtonEnable(ListViewAdapter.ENABLE);
                    printerInfoText.setText("已连接");
                    mPortParam.setPortOpenState(true);
                } else if (type == GpDevice.STATE_INVALID_PRINTER) {
                    setProgressBarIndeterminateVisibility(false);
//					SetLinkButtonEnable(ListViewAdapter.ENABLE);
                    printerInfoText.setText("已连接");
                    Toast.makeText(getApplicationContext(), "Please use Gprinter!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };
}
